<?php


namespace ke;


use app\admin\validate\ArticleValidate;
use app\common\library\FormDataValidate;
use think\facade\Request;

class AutoModel extends Model
{
    public function autoSave($validate, array $options = [])
    {
        $id = Request::post('id/d');
        $form = new FormDataValidate($validate, $id ? 'edit' : 'add');

        if (isset($options['before'])) {
            call_user_func_array($options['before'], $form);
        }
        $response = [];
        if (isset($form->id)) {
            $data = static::where('id', $form->id)
                ->where($options['where'] ?? null)
                ->findOrFail();
            $response['type'] = 'update';
            $response['data'] = $data;
        } else {
            $data = new static;
            $response['type'] = 'insert';
        }
        $data->save($form->toArray());
        if (isset($options['after'])) {
            $data = call_user_func_array($options['after'], $data);
        }
        $response['data'] = $data;

        return $response;
    }

}